var express = require("express");
var router = express.Router();
const adminService = require("../service/adminService");

// 引入token
const { secretKey, sha256 } = require("../utils/token");
const jwt = require("jsonwebtoken");
// 注册
router.post("/reg", async function (req, res, next) {
  let { username, password, name, age, gender, phone, position, status } =
    req.body.params;
  let result = await adminService.find(username); // 查询账号是否存在？
  if (result) {
    await adminService.regAdmin({
      username,
      password: sha256(password),
      name,
      age,
      gender,
      phone,
      position,
      status,
    });
    res.send(result);
  } else {
    res.send(result);
  }
});
// 登录
router.get("/login", async function (req, res, next) {
    console.log("we",req.query);
  const { username, password } = req.query;
  let data = await adminService.login({ username, password: sha256(password) });
  console.log(data);
  if (Object.keys(data).length > 0) {
    // 生成token
    let authToken = jwt.sign({ user: data }, secretKey);
    // 将生成的token返回
    res.send({ data, token: authToken });
  } else {
    res.send(data);
  }
});
// 获取平台管理员数据
router.get("/adminList", async function (req, res, next) {
  let { current, size } = req.query;
  let data = await adminService.adminList({ current: current || 1, size: size || 5 });
  res.send(data);
});

// 条件获取平台管理员数据
router.get("/adminCondition", async function (req, res, next) {
    console.log(req.query);
    let { type, value,type2, value2, current, size } = req.query;
    let searchObj = {};
    if (type) { searchObj[type] = { $regex: value } }   // 使用正则可以实现模糊查询
    if (type2) { searchObj[type2] = { $regex: value2 } }   // 使用正则可以实现模糊查询
    console.log(searchObj);
    let data = await adminService.adminCondition(searchObj,{ current: current || 1, size: size || 5 });
    res.send(data);
});


// 删除管理员数据
router.delete("/deleteId", async function (req, res, next) {
  let { id } = req.query;
  await adminService.deleteAdmin({ id });
  res.send({})
});



//修改匹配
router.put('/:id', async function (req, res) {

    let data = await adminService.update(req.params.id, req.body)
    res.send(data);
})



module.exports = router;













